/**
 * Created by arvin on 2017/4/22.
 */

var Bearcat = require('bearcat');
var Async = require("async")

module.exports = function () {
    return Bearcat.getBean({
        id: "get-login",
        func: login,
        props: [
            {name: "app", "ref": "application"}
        ]
    });
}

function login() {
    this.app = null;
}

var CheckMotionDevice = function (msg) {
    if(msg.params.motion == undefined || msg.params.name== undefined ||msg.params.pwd == undefined)
        return false;
    //  if(msg.params.motion.length != 40)
    //    return false;
    return true;
}

login.prototype.handle = function (msg,next) {

    if(!CheckMotionDevice(msg))
    {
        next(null,{code:4,msg:""});
        return;
    }
    var model = this.app.getComponent("dao").getConnection().model("adminMsg");
    var name = msg.params.name;
    var motion = msg.params.motion;
    var pwd = msg.params.pwd;
    Async.waterfall(
        [

            function () {
                model.invalidate(motion,function (data) {

                    if (data == null)
                    {
                        next(null,{code:4,msg:"这个账户不是对应这台机器"});
                        return;
                    }
                    if ( data.MotionDevice != motion )
                    {
                        next(null,{code:4,msg:"这个账户不是对应这台机器"});
                        return;
                    }

                    if ( data.Admin != name  )
                    {
                        next(null,{code:3,msg:"用户名不正确"});
                        return;
                    }

                    if( data.UsedTime >=10 )
                    {
                        next(null,{code:5,msg:"大于规定次数"});
                        return;
                    }

                    data.UsedTime++;
                    model.UpdateAdmin( {MotionDevice:motion,UsedTime:data.UsedTime});
                    next(null,{code:1,msg:data.UsedTime});
                })
            },
        ]
    );

}